use anyhow::Result;
use db::Db;
use matrix_sdk::{
    room::Room,
    ruma::events::room::message::{
        OriginalSyncRoomMessageEvent, Relation, RoomMessageEventContent,
    },
    Client,
};

pub async fn unarchive(
    ev: OriginalSyncRoomMessageEvent,
    _text: String,
    room: Room,
    _client: Client,
    db: Db,
) -> Result<()> {
    let relation = ev.content.relates_to.unwrap();
    if let Relation::Reply { in_reply_to } = relation {
        let event_id = in_reply_to.event_id.to_string();
        if let Some(userpost_id) = db.get_userpost_id(event_id).await? {
            log::info!("unarchiving");
            db.unarchive_post(userpost_id).await.unwrap();
            let content = RoomMessageEventContent::text_markdown("unarchived");
            room.send(content).await.unwrap();
            log::info!("unarchived post");
        }
    }
    Ok(())
}

fn clear_label(text: String) -> String {
    if text.contains("[Archived]") {
        text.strip_suffix("[Archived]").unwrap().to_string()
    } else {
        text
    }
}
